<template>
  <div class="seniorSearchForm">
    <el-form
      :model="dynamicValidateForm"
      ref="dynamicValidateForm"
      label-width="100px"
      class="demo-dynamic"
    >
      <div
        v-for="(domain, index) in dynamicValidateForm.domains"
        :key="domain.key"
        class="dynamicItem"
      >
        <div class="andOr" v-if="index != 0">
          {{ domain.searchType == "and" ? "与" : "或" }} 
        </div>
        <el-form-item required>
          <el-col :span="2">
            <el-form-item
              :prop="'domains.' + index + '.searchProperty'"
              :rules="{
                required: true,
                message: '请选择内容',
                trigger: 'change',
              }"
            >
              <el-select
                filterable
                v-model="domain.searchProperty"
                placeholder="请选择内容"
                @change="conditionChange(index, $event)"
              >
                <el-option
                  v-for="item in conditionOpts || domain.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item
              :prop="'domains.' + index + '.searchRule'"
              :rules="{
                required: true,
                message: '请选择内容',
                trigger: 'change',
              }"
            >
              <el-select
                v-model="domain.searchRule"
                placeholder="请选择内容"
                @change="symbolChange(index, $event, domain.options)"
              >
                <el-option
                  v-for="item in domain.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item
              :prop="'domains.' + index + '.searchValue'"
              :rules="{
                required: true,
                message: '请输入内容',
                trigger: 'change',
              }"
            >
              <el-input
                v-if="domain.type == 'number'"
                v-model.trim="domain.searchValue"
                placeholder="请输入内容"
                @keyup.native="numKeyUp($event, domain)"
              ></el-input>
              <el-select
                v-else-if="domain.type == 'dict'"
                v-model="domain.searchValue"
                placeholder="请选择内容"
              >
                <el-option
                  v-for="item in domain.valueOpts"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model.trim="domain.searchValue"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
          <i
            class="del-icon el-icon-delete-solid"
            @click="removeDomain(domain)"
          ></i>
        </el-form-item>
      </div>

      <el-form-item class="btn-item">
        <el-button @click="addDomain('and')">新增与条件</el-button>
        <el-button
          v-if="
            dynamicValidateForm.domains && dynamicValidateForm.domains.length
          "
          @click="addDomain('or')"
          >新增或条件</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/** conditionOpts 参数解析
  * label：中文释义
  * value：对应code值
  * colRules：对应规则（大于，小于等计算规则）
  * type：类型（input，select）
*/
export default {
  name: 'SeniorSearchForm',
  model: {
    prop: "dynamicValidateForm",
    event: "formChange",
  },
  props: {
    conditionOpts: {
      type: Array,
      default: () => {
        [];
      },
    },
    // symbolOpts: {
    //   type: Array,
    //   default: () => {
    //     [];
    //   },
    // },
    dynamicValidateForm: {
      type: Object,
      default: () => ({
        domains: [
          {
            searchProperty: "",
            searchRule: "",
            searchValue: "",
            searchType: "and",
            key: Date.now(),
            type: ''
          },
        ],
      }),
    },
    // 高级查询字典值
    dictValue: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      // conditionOpts: [],
      symbolOpts: [],
      valueOpts: [],
    };
  },
  computed: {},
  watch: {},
  created() {},
  async mounted() {
    // let conditionOpts = await listByType(this.dictValue);
    // this.conditionOpts = conditionOpts.map((e) => {
    //   return {
    //     label: e.colLabel,
    //     value: e.colValue,
    //     colRules: e.colRules,
    //     type: e.inputType,
    //   };
    // });
  },
  methods: {
    numKeyUp(e, item) {
      if (item.dataType == "float") {
        e.target.value = e.target.value.match(/\d+\.?\d{0,2}/, "");
      } else {
        e.target.value = e.target.value.replace(/[^\d]/g, "");
      }
      domain.searchValue = e.target.value;
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs["dynamicValidateForm"].validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    addDomain(val) {
      this.dynamicValidateForm.domains.push({
        searchProperty: "",
        searchRule: "",
        searchValue: "",
        searchType: val,
        key: Date.now(),
        type: ''
      });
    },
    resetDomain() {
      this.$emit("formChange", {
        domains: [
          {
            searchProperty: "",
            searchRule: "",
            searchValue: "",
            searchType: "and",
            key: Date.now(),
            type: ''
          },
        ],
      });
    },
    conditionChange(ind, $event) {
      // 第一个下拉框值改变后，清空第二个值，第三个值、第三个下拉框值
      this.$set(this.dynamicValidateForm.domains[ind], 'searchRule', '')
      this.$set(this.dynamicValidateForm.domains[ind], 'options', [])
      this.$set(this.dynamicValidateForm.domains[ind], 'searchValue', '')
      this.$set(this.dynamicValidateForm.domains[ind], 'valueOpts', [])
      
      let obj = this.conditionOpts.find((e) => e.value == $event);
      this.$nextTick(() => {
        this.$set(this.dynamicValidateForm.domains[ind], 'options', obj ? obj.colRules : [])
        this.$set(this.dynamicValidateForm.domains[ind], 'type', obj ? obj.type : '')
      })
    },
    symbolChange(ind, $event, opts) {
      // 第二个下拉框值改变后，清空第三个值、第三个下拉框值
      this.$set(this.dynamicValidateForm.domains[ind], 'searchValue', '')
      this.$set(this.dynamicValidateForm.domains[ind], 'valueOpts', [])
      let obj = opts.find(e => e.value == $event)
      this.$nextTick(() => {
        this.$set(this.dynamicValidateForm.domains[ind], 'valueOpts', obj ? obj.dictValueList : [])
      })
      this.$emit("symbolChange", ind, $event);
    },
  },
};
</script>

<style scoped lang='scss'>
.seniorSearchForm {
  padding: 16px;
  max-height: 178px;
  background: #f7f8fa;
  // border-top: 1px solid #e5e6eb;
  overflow: auto;
  .dynamicItem {
    ::v-deep .el-form-item {
      margin-bottom: 0;
    }
  }
  ::v-deep .el-form-item__content {
    margin-left: 0 !important;
    .el-col {
      margin-right: 10px;
    }
  }
  .btn-item {
    margin-top: 15px;
    margin-bottom: 0;
  }
  .andOr {
    margin: 2px 0;
  }
  .del-icon {
    font-size: 20px;
    margin-left: 10px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>